import {getUserInfo, login} from "@/api/user";
import {getToken, removeToken, setToken} from "@/utils/verifyToken";

const state={
  username: '',
  avatar: '',
  email:'',
  roles: [],
  userId:'',
  token: getToken(),
}
const mutations={
  SET_USERNAME(state,username){
    state.username=username
  },
  SET_AVATAR(state,avatar){
    state.avatar=avatar;
  },
  SET_EMAIL(state,email){
    state.email=email;
  },
  //角色分为admin和guest和guest，user三种
  SET_ROLES(state,roles){
      state.roles=roles
  },

  SET_USERID(state,userId){
    state.userId=userId;
  },
  SET_TOKEN(state,token){
    state.token=token;
  }
}

const actions={
  //处理登录，组件dispatch过来后使用
 handleLogin({ commit }, userInfo){
     const { username, password } = userInfo
     return new Promise((resolve, reject) => {
       login(username,password).then(res=> {
         const { data } = res
         commit('SET_TOKEN', data.token)
         setToken(data.token)
         resolve(data)
       }).catch(error => {
         reject(error)
       })
     })
 },
  getUserInfo({commit}){
    return new Promise((resolve, reject) => {
      getUserInfo(getToken()).then(response => {
        const { data } = response

        if (!data) {
          reject('验证失败，请重新登录。')
        }
        const { roles, username, userAvatar, userEmail,userId } = data

        // roles不能为空
        if (!roles || roles.length <= 0) {
          reject('roles不能为空')
        }
        commit('SET_USERNAME', username)
        commit('SET_AVATAR', userAvatar)
        commit('SET_EMAIL', userEmail)
        commit('SET_ROLES', roles)
        commit('SET_USERID', userId)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  //登出，删除令牌
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', removeToken())
      commit('SET_ROLES', [])
      commit('SET_USERNAME', '')
      commit('SET_AVATAR', '')
      commit('SET_EMAIL', '')
      commit('SET_USERID', '')
      removeToken()
      resolve()
    })
  }
}
//导出模板
export default {
  namespaced:true,
  state,
  mutations,
  actions
}
